package com.newear.marathon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newear.marathon.dto.admin.inquiry.*;
import com.newear.marathon.dto.admin.maintenance.*;
import com.newear.marathon.entity.admin.AdminResource;
import com.newear.marathon.mapper.AdminResourceMapper;
import com.newear.marathon.service.IAdminResourceService;
import com.newear.marathon.utils.ApplicationError;
import com.newear.marathon.utils.BaseException;
import com.newear.marathon.utils.TransactionStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MicroBin
 * @since 2019-08-14
 */
@Slf4j
@Service
public class AdminResourceServiceImpl extends ServiceImpl<AdminResourceMapper, AdminResource> implements IAdminResourceService
{

    @Autowired
    private AdminResourceMapper adminResourceMapper;

    @Override
    public AdminResourceLoopInquiryResponseDTO doResourceInquiryLoop(AdminResourceLoopInquiryRequestDTO requestDTO)
    {
        log.info("doResourceInquiryPage start");
        AdminResourceLoopInquiryResponseDTO responseDTO = new AdminResourceLoopInquiryResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();

        QueryWrapper<AdminResource> wrapper = new QueryWrapper<>();
        //wrapper.eq("system_id",requestDTO.getSystemId());
        wrapper.select("id", "parent_id", "name", "permission", "icon", "url", "priority", "type", "available");
        wrapper.orderByAsc("priority");
        List<AdminResource> all = list(wrapper);
        List<AdminResourceLoopInquiryResponseSubDTO> result = new ArrayList<>();
        all.forEach(w -> {
            AdminResourceLoopInquiryResponseSubDTO responseSubDTO = new AdminResourceLoopInquiryResponseSubDTO();
            BeanUtils.copyProperties(w, responseSubDTO);
            result.add(responseSubDTO);
        });
        responseDTO.setDataList(result);
        responseDTO.setTransactionStatus(transactionStatus);
        log.info("doResourceInquiryPage end");
        return responseDTO;
    }

    @Transactional
    @Override
    public AdminResourceAdditionResponseDTO doResourceAddition(AdminResourceAdditionRequestDTO requestDTO)
    {
        log.info("doResourceAddition start");
        AdminResourceAdditionResponseDTO responseDTO = new AdminResourceAdditionResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();

        //判断同级的资源名称是否重复
        QueryWrapper<AdminResource> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", requestDTO.getParentId());
        wrapper.eq("name", requestDTO.getName());
        wrapper.eq("available", 1);
        AdminResource resource1 = getOne(wrapper);
        if (null != resource1)
        {
            throw new BaseException(ApplicationError.NAME_SAME.getMessage(), ApplicationError.NAME_SAME.getCode());
        }

        //查询父节点信息，组装parentIds
        QueryWrapper<AdminResource> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id", requestDTO.getParentId());
        AdminResource parentResource = getOne(wrapper1);
        if (null == parentResource)
        {
            throw new BaseException(ApplicationError.NOT_EXIST_PARENTID.getMessage(), ApplicationError.NOT_EXIST_PARENTID.getCode());
        }
        String parentIds = parentResource.getParentIds() + requestDTO.getParentId() + "/";

        AdminResource resource = new AdminResource();
        BeanUtils.copyProperties(requestDTO, resource);
        resource.setParentIds(parentIds);
        save(resource);

        responseDTO.setTransactionStatus(transactionStatus);
        log.info("doResourceAddition end");
        return responseDTO;
    }

    @Override
    public AdminResourceModifyInquiryResponseDTO doResourceModifyInquiry(AdminResourceModifyInquiryRequestDTO requestDTO)
    {
        log.info("doResourceModifyInquiry start");
        AdminResourceModifyInquiryResponseDTO responseDTO = new AdminResourceModifyInquiryResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();

        QueryWrapper<AdminResource> wrapper = new QueryWrapper<>();
        wrapper.eq("id", requestDTO.getId());
        wrapper.select("id", "name", "permission", "icon", "url", "priority", "type", "available");
        AdminResource resource = getOne(wrapper);
        if (null != resource)
        {
            BeanUtils.copyProperties(resource, responseDTO);
        }

        responseDTO.setTransactionStatus(transactionStatus);
        log.info("doResourceModifyInquiry end");
        return responseDTO;
    }

    @Transactional
    @Override
    public AdminResourceModifyResponseDTO doResourceModify(AdminResourceModifyRequestDTO requestDTO)
    {
        log.info("doResourceModify start");
        AdminResourceModifyResponseDTO responseDTO = new AdminResourceModifyResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();
        //判断：如果available=0，不让更新
        Integer available = getResourceStatus(requestDTO.getId());
        if (1 != available)
        {
            throw new BaseException(ApplicationError.RESOURCE_NOT_UPDATE.getMessage(), ApplicationError.RESOURCE_NOT_UPDATE.getCode());
        }

        AdminResource resource = new AdminResource();
        BeanUtils.copyProperties(requestDTO, resource);
        //更新操作
        Boolean result = updateById(resource);
        if (!result)
        {
            throw new BaseException(ApplicationError.MODIFY_FAILED.getMessage(), ApplicationError.MODIFY_FAILED.getCode());
        }
        responseDTO.setTransactionStatus(transactionStatus);
        log.info("doResourceModify end");
        return responseDTO;
    }

    public Integer getResourceStatus(Integer resourceId)
    {
        QueryWrapper<AdminResource> wrapper = new QueryWrapper<>();
        wrapper.eq("id", resourceId);
        wrapper.select("available");
        AdminResource adminResource = getOne(wrapper);
        if (null != adminResource)
        {
            return adminResource.getAvailable();
        }
        else
        {
            throw new BaseException(ApplicationError.MODIFY_FAILED.getMessage(), ApplicationError.MODIFY_FAILED.getCode());
        }
    }

    @Transactional
    @Override
    public AdminResourceModifyStatusResponseDTO doResourceModifyStatus(AdminResourceModifyStatusRequestDTO requestDTO)
    {
        log.info("doResourceModifyStatus start");
        AdminResourceModifyStatusResponseDTO responseDTO = new AdminResourceModifyStatusResponseDTO();
        TransactionStatus transactionStatus = new TransactionStatus();

        AdminResource resource = new AdminResource();
        BeanUtils.copyProperties(requestDTO, resource);
        //更新操作
        Boolean result = updateById(resource);
        if (!result)
        {
            throw new BaseException(ApplicationError.DELETE_FAILED.getMessage(), ApplicationError.DELETE_FAILED.getCode());
        }

        responseDTO.setTransactionStatus(transactionStatus);
        log.info("doResourceModifyStatus end");
        return responseDTO;
    }

    @Override
    public List<AdminResource> findByUserId(Integer userId)
    {
        List<AdminResource> resourceList = adminResourceMapper.findByUserId(userId);
        return resourceList;
    }

}
